package com.kehutong.payment.service;

import com.kehutong.payment.dto.OrderRefundResDto;
import com.kehutong.payment.entity.OrderRefund;
import com.kehutong.payment.entity.ThirdOrder;
import com.kehutong.payment.util.PayUtil;
import com.kehutong.payment.util.UUIDUtils;
import com.kehutong.payment.util.WechatHttpUtils;
import com.kehutong.payment.util.WechatSignUtils;
import com.kehutong.payment.vo.Merchant;
import org.coraframework.inject.Inject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信退款接口
 *
 * @author wupengfei
 */
public class WechatRefundServiceImpl extends AbstractRefundService {

    private static final Logger logger = LoggerFactory.getLogger(WechatRefundServiceImpl.class);

    @Inject
    private RouteService routeService;

    @Override
    public OrderRefundResDto doRefundOrder(ThirdOrder thirdOrder, OrderRefund orderRefund) throws Exception {
        logger.info("微信退款orderId=" + thirdOrder.getId() + ", orderFee=" + thirdOrder.getOrderFee());

        // 返回结果
        OrderRefundResDto result = new OrderRefundResDto();
        result.setThirdOrderId(thirdOrder.getId());

        // 查询商户配置
        Merchant merchant = routeService.routeV2(thirdOrder.getCompanyNo(), thirdOrder.getCommunityNo());

        // 组装查询微信订单的参数
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("appid", thirdOrder.getAppId());
        paramsMap.put("mch_id", thirdOrder.getMchId());
        paramsMap.put("sub_mch_id", thirdOrder.getSubMchId());
        paramsMap.put("nonce_str", UUIDUtils.getUuid());
        paramsMap.put("out_trade_no", thirdOrder.getId());
        paramsMap.put("sign_type", "MD5");
        paramsMap.put("out_refund_no", orderRefund.getTradeNo());
        paramsMap.put("total_fee", thirdOrder.getOrderFee() + "");
        paramsMap.put("refund_fee", orderRefund.getRefundMoney() + "");
        paramsMap.put("sign", WechatSignUtils.generateSignature(paramsMap, merchant.getMchSecret(), WechatSignUtils.MD5));
        String respXml = WechatHttpUtils.post("https://api.mch.weixin.qq.com/secapi/pay/refund", paramsMap, true, merchant.getSslContext(), merchant.getMchId());
        logger.info("微信退款结果respXml=" + respXml);

        Map<String, String> respMap = PayUtil.xmlToMap(respXml);
        boolean sign = WechatSignUtils.isSignatureValid(respMap.get("return_code"), respMap.get("result_code"),
                respMap, merchant.getMchSecret(), WechatSignUtils.MD5);
        if (sign) {
            result.setFirstSuccess(true);
            result.setSuccess(true);
            result.setRefundDate(new Date());
            result.setVendorTradeNo(respMap.get("refund_id"));
            logger.info("订单退款成功");
        } else {
            if (WechatSignUtils.SUCCESS.equals(respMap.get("return_code")) && "OK".equals(respMap.get("return_msg")) && "订单已全额退款".equals(respMap.get("err_code_des"))) {
                result.setSuccess(true);
            } else {
                logger.info("订单退款失败，签名有误");
            }
        }
        result.setDescription(respMap.get("err_code_des"));
        return result;
    }

}
